package top.jacktgq.hsp.netty.protobuf.codec.v1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * @Author CandyWall
 * @Date 2020/11/12--13:34
 * @Description Netty入门：客户端
 */
public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup eventExecutors = null;
        try {
            //客户端需要一个事件循环组
            eventExecutors = new NioEventLoopGroup();

            //创建客户端启动对象
            //注意客户端使用的不是ServerBootStrap，而是BootStrap
            Bootstrap bootstrap = new Bootstrap();

            //设置相关参数
            bootstrap.group(eventExecutors)     //设置线程组
                    .channel(NioSocketChannel.class)   //设置客户端通道的实现类
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //需要添加一个编解码器，不然收不到信息
                            //在Pipeline中加入ProtoBufEncoder
                            pipeline.addLast("encoder", new ProtobufEncoder());

                            pipeline.addLast(new NettyClientHandler());   //加入自己的处理器类
                        }
                    });
            System.out.println("客户端准备好了...");

            //启动客户端去连接服务器端
            //关于ChannelFuture要分析，涉及到netty的异步模型
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();

            //给关闭的通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventExecutors.shutdownGracefully();
        }
    }
}
